#!/usr/bin/perl -w
use strict;
use warnings;
use File::Copy;

$|++;

for my $file (@ARGV) {
	my $libs = {};
	my $libdirs = {};
	my $frameworks = {};
	my $framedirs = {};
	my $staticlibs = {};
	my $last_word = "";
	copy($file, $file . '.orig');
	open (FILEIN, $file) or die "could not read $file: $!\n";
	open (FILEOUT, '>' . $file . '.new') or die "could not write to $file.new: $!\n";
	FILELOOP: while (my $line = <FILEIN>) {
		for my $word (split(/\s+/, $line)) {
			if ($word =~ /\/ar$/) {
				print FILEOUT $line;
				next FILELOOP;
			}
			if ($last_word eq "-framework") {
				if (exists $frameworks->{$word}) {
					$last_word = $word;
					next;
				}
				$frameworks->{$word}++;
				print FILEOUT "-framework ";
			}
			$last_word = $word;

			if ($word =~ /^-l/) {
				next if (exists $libs->{$word});
				$libs->{$word}++;
			}
			if ($word =~ /^-L/) {
				next if (exists $libdirs->{$word});
				$libdirs->{$word}++;
			}
			if ($word =~ /^-F/) {
				next if (exists $framedirs->{$word});
				$framedirs->{$word}++;
			}
			if ($word =~ /\.a$/) {
				next if (exists $staticlibs->{$word});
				$staticlibs->{$word}++;
			}

			next if ($word eq "-framework");
			print FILEOUT $word, " ";
		}
		print FILEOUT "\n";
	}
	close (FILEOUT);
	close (FILEIN);
	move($file . '.new', $file);
}
